<?php

namespace App\Http\Controllers;


use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\FsUserHasIm;
use Illuminate\Http\Request;

class FsUserHasImController extends Controller
{
    /**
     * @api {post} /api/fsUserHasIm 会员微信添加
     * @apiGroup FsUserHasIm
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} wx  微信号
     * @apiParam {int} fs_user_id  会员Id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 201 OK
     */
    public function store(Request $request,FsUserHasIm $fsUserHasIm){
        $data = $request->validate([
            'fs_user_id'=>'required|exists:mysql_branch.fs_user,id',
            'wx' => 'required|max:30',
        ]);
        $res  = $fsUserHasIm->where('fs_user_id',$data['fs_user_id'])->first();
        if($res && !empty($res['wx'])){
            return response()->json(['error' => '已添加微信'], 422);
        }
        if($res){
            $data['created_at'] = Carbon::now();
            DB::table('fs_user_has_ims')->where('fs_user_id',$data['fs_user_id'])->update($data);
            $res->update($data);
        }else{
            $fsUserHasIm->create($data);
        }

        return $this->response->created();
    }

    /**
     * @api {patch} /api/fsUserHasIm 会员微信修改
     * @apiGroup FsUserHasIm
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} wx  微信号
     * @apiParam {int} fs_user_id  会员Id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *             "message": "修改成功"
     *       }
     */
    public function update(Request $request,FsUserHasIm $fsUserHasIm){
        $data = $request->validate([
            'fs_user_id'=>'required|exists:mysql_branch.fs_user,id',
            'wx' => 'required|max:30',
        ]);
        $fsUserHasIm->where('fs_user_id',$data['fs_user_id'])->update($request->only('wx'));

        return response()->json(['message' => '修改成功']);
    }

}
